package com.wxy.student.service.impl;
 
import com.wxy.student.dao.GradeDao;
import com.wxy.student.dao.StudentDao;
import com.wxy.student.entity.Grade;
import com.wxy.student.entity.Student;
import com.wxy.student.entity.StudentInfo;
import com.wxy.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl implements StudentService {
 
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private GradeDao gradeDao;
 
    @Override
    public Student save(Student student) {


        return studentDao.save(student);
    }
 
    @Override
    public Student update(Student student) {

        return studentDao.save(student);
    }
 
    @Override
    public void delete(Integer id) {
        studentDao.deleteById(id);
    }

 

    @Override
    public List<Student> findAll() {

        return studentDao.findAll();
    }

    @Override
    public List<Student> findByGradeId(Integer gradeId) {
        return studentDao.findByGradeId(gradeId);
    }
    @Override
    public List<StudentInfo> list( ) {
        List<Student> list = studentDao.list();
        List<Grade> all = gradeDao.findAll();
        List<StudentInfo> collect = list.stream().map(l -> {

            Optional<Grade> first = all.stream().filter(a -> a.getId() == l.getGradeId()).findFirst();
            if (first.isPresent()) {
                StudentInfo build = build(l);
                build.setGradeName(first.get().getName());
                return build;
            }
            return null;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        return collect ;
    }

    public StudentInfo build(Student student){
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setId(student.getId());
        studentInfo.setName(student.getName());
        studentInfo.setAddress(student.getAddress());
        studentInfo.setSex(student.getSex());
        return studentInfo;
    }
    @Override

    public void deleteByGradeId(Integer id) {
        studentDao.deleteByGradeId(id);
        studentDao.deleteByStudentGrade(id);
        gradeDao.deleteGradeId(id);
    }
}